package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;


    /**
     * 处理超时的订单
     * 把订单状态修改为已取消
     */
    @Scheduled(cron = "0/5 * * * *  ?")
    public void handlerTimeOutOrder() {
        log.info("处理未支付超时订单");
        // 当前时间减去15分钟
        LocalDateTime dateTime = LocalDateTime.now().minusMinutes(15);
        // 根据订单状态(1 待付款),超时时间
        List<Orders> orders = orderMapper.getByStatusWithTimeLT(Orders.PENDING_PAYMENT, dateTime);
        // 修改订单状态为已取消
        orders.forEach(order -> {
            order.setStatus(Orders.CANCELLED);
            order.setCancelReason(MessageConstant.ORDER_TimeOut);
            order.setCancelTime(LocalDateTime.now());
            orderMapper.updateOrder(order);
        });
    }
}
